package registry

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
)

type Service struct{}

func (s Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Println("Registry received")
	switch r.Method {
	case http.MethodPost:
		decoder := json.NewDecoder(r.Body)
		var registration Registration
		err := decoder.Decode(&registration)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		log.Printf("Adding service: %v with URL: %s\n",
			registration.ServiceName, registration.ServiceURL)

		err = reg.add(registration)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}

	case http.MethodDelete:
		payload, err := io.ReadAll(r.Body)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		serviceName := ServiceName(payload)
		log.Printf("Removing service : %v", serviceName)
		err = reg.remove(serviceName)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}

	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
}
